<template>
  <zm-view background="#F4F6F7">
    <view class="px-30 py-32">
      <!-- 顶部添加券 -->
      <view class="flex items-center font-24 mb-20">
        <view class="text-999">
          <text>可使用</text>
          <text class="pl-12"> ({{ canUseNum }})</text>
        </view>
        <view class="flex ml-auto text-333 items-center" @click="toView({ url: 'pages/person/film-card-add/film-card-add' })">
          <view class="p-8">添加绑定</view>
          <zm-icon name="add-o" size="32rpx"></zm-icon>
        </view>
      </view>
      <!-- 可用卡列表 -->
      <film-card
        v-for="item in cardCanUseList"
        :key="item.cardId"
        custom-class="mt-20"
        show-type="select"
        :disabled="false"
        :selected="checkId === item.cardId"
        :info="item"
        @click="handleCheck"
      >
        <view v-if="checkId === item.cardId" slot="footer" class="flex items-center text-999 px-30 py-20">
          <text>已抵扣</text>
          <text :style="[useThemeStyle()]">{{ topPoint }}</text>
          <text>点</text>
        </view>
      </film-card>
      <zm-empty v-if="canUseNum == 0 && !loading && cardUnUseList.length == 0" text="暂无可用" :icon="useImage('/zuimei-film-oss/1.0.0/empty/zwdyk-empty.png')"></zm-empty>
      <!-- 不可用卡列表 -->
      <view v-if="unUseNum > 0" class="flex font-24 my-20">
        <view class="text-999">
          <text>不可使用</text>
          <text class="pl-12"> ({{ unUseNum }})</text>
        </view>
      </view>
      <film-card v-for="item in cardUnUseList" :key="item.cardId" custom-class="mt-20" show-type="select" :disabled="true" :info="item">
        <!-- 不可用提示 -->
        <view v-if="!item.usable && item.errorMsg" slot="footer" class="flex items-center text-999 px-30 py-20">
          {{ item.errorMsg }}
        </view>
      </film-card>
    </view>
    <zm-footer safe-area-inset-bottom z-index="10" background="#fff">
      <view class="px-30 py-20 bg-white flex items-center justify-end">
        <view class="font-26 text-999 mr-16">还需支付</view>
        <view class="text-price-before mr-20 text-price font-34 font-bold">{{ needPay }}</view>
        <zm-button width="290rpx" height="88rpx" type="primary" text-size="32rpx" text-weight="600" round @click="submit">确定</zm-button>
      </view>
    </zm-footer>
  </zm-view>
</template>

<script>
/**
 * isCashDiff 点卡是否开启现金补差模式 0否 1是
 */
import page from "@/mixins/page"
import store from "@/store"
import { mapGetters } from "vuex"
export default {
  mixins: [page],
  data() {
    return {
      loading: true,
      checkId: "",
      topPoint: "",
      cardCanUseList: [],
      cardUnUseList: [],
      orderId: "",
      cutPrice: 0,
      needPay: 0
    }
  },
  onLoad(options) {
    uni.setNavigationBarTitle({ title: `选择${this.cardName}` })
    this.orderId = options.orderId
    this.init()
  },

  computed: {
    ...mapGetters(["couponCardMergeUse", "checkCard", "orderInfo", "checkCoupon", "checkParams", "cardName"]),
    isMaxCard() {
      return this.orderInfo.uCCR.card == "1"
    },
    canUseNum() {
      return this.cardCanUseList.length
    },
    unUseNum() {
      return this.cardUnUseList.length
    },
    cardDisabled() {
      // true 时候电影卡不可以抵扣座位数(可抵扣数量已经被券抵扣完了,此时能使用的只有caseDiff为1的补差卡)
      return this.checkParams.cardDisabled
    }
  },
  watch: {
    cutPrice: {
      handler(val) {
        const card = this.getCheckCard()
        const needPoint = +card.needPoint || 0
        const cutPoint = needPoint == 0 ? 0 : this.$u.divide(val, needPoint)
        let prePrice = 0
        if (!this.couponCardMergeUse && this.checkParams.coupons?.length && this.cardCanUseList.length) {
          prePrice = this.checkParams.filmPrice // 要支付的总金额
        } else {
          prePrice = this.checkParams.prePrice // 要支付的总金额
        }
        this.needPay = this.$u.minus(prePrice, val)
        this.topPoint = +cutPoint
      },
      immediate: true
    }
  },

  methods: {
    init() {
      this.checkId = this.checkParams.cardId
      if (this.orderId) {
        this.getCardByOrderFilm()
      } else {
        this.getCardPay()
      }
    },
    // 影片订单列表
    getCardByOrderFilm() {
      uni.$api.card.getCardByOrderFilm({ orderId: this.orderId }, { login: true }).then((res) => {
        res.map((item) => {
          item.money = this.$u.times(+item.point, +item.needPoint)
          // 不可用 || 不可补差且座位数被券抵扣完
          !item.usable || (item.isCashDiff == "0" && this.cardDisabled) ? this.cardUnUseList.push(item) : this.cardCanUseList.push(item)
        })
        this.loading = false
        this.getCutPrice()
      })
    },
    getCheckCard() {
      return this.cardCanUseList.find((i) => i.cardId === this.checkId) || {}
    },
    getCutPrice() {
      const card = this.getCheckCard()
      let prePrice = 0
      if (!this.couponCardMergeUse && this.checkParams.coupons && this.checkParams.coupons.length > 0) {
        // 卡券不可同时使用，价格回到总的
        prePrice = this.checkParams.filmPrice // 要支付的总金额
      } else {
        // 卡券可以同时使用，扣除券剩余要支付价格
        prePrice = this.checkParams.prePrice // 要支付的总金额
      }
      let cutPrice = 0
      const isAllDeduction = card.isCashDiff == "1" // 是否开启补差抵扣
      // 卖品支付时候使用
      // if (uni.$fromRoute == "goods-pay") {
      //   const topMoney = +card.topMoney
      //   cutPrice = topMoney > prePrice ? prePrice : topMoney
      //   this.setData({
      //     cutPrice: +cutPrice
      //   })
      //   return
      // }

      const needPoint = +card.needPoint // 转换率
      const cardPoint = +card.point // 卡点
      const cardMoney = this.$u.times(cardPoint, needPoint) // 卡金额
      if (isAllDeduction) {
        // 支付无座位限制
        this.cutPrice = cardMoney > prePrice ? prePrice : cardMoney
        console.log("开启补差：", this.cutPrice)
        return
      }
      let canUseCardList = this.orderInfo.seatList.map((i, idx) => {
        return {
          ...i,
          sort: idx,
          finalPrice: i.salePrice
        }
      }) // 座位列表
      if (this.couponCardMergeUse && this.checkParams.coupons && this.checkParams.coupons.length > 0) {
        this.checkParams.coupons.forEach((i, idx) => {
          i.sort = idx
        })
        canUseCardList = this.checkParams.coupons.filter((i) => !i.couponId && i.finalPrice > 0) // 可用卡抵扣座位
      }
      let priceCombine = []
      if (cardMoney) {
        let toCombieArr = [canUseCardList]
        for (let i = 0; i < canUseCardList.length; i++) {
          if (i > 0) {
            toCombieArr.push(canUseCardList)
          }
          priceCombine = priceCombine.concat(this.doCombination(toCombieArr))
        }
        const filterSeatPrice = priceCombine.filter((i) => {
          const arr = i.sort((a, b) => {
            return this.$u.minus(+a.sort, +b.sort)
          })
          const seatNoArr = arr.map((j) => j.seatNo)
          const seatSet = new Set(seatNoArr)
          return seatSet.size === seatNoArr.length
        })
        const filterSeatPriceJSON = filterSeatPrice.map((i) => {
          return JSON.stringify(i)
        })
        const filterAfterSet = new Set(filterSeatPriceJSON)
        const finalSeatPrice = [...filterAfterSet].map((i) => {
          return JSON.parse(i)
        })
        console.log(finalSeatPrice, "过滤重复后：finalSeatPrice")
        const finalUseCardPrice = finalSeatPrice.map((i) => {
          const price = i.reduce((t, v) => {
            return this.$u.plus(+t, +v.finalPrice)
          }, 0)
          return {
            price,
            seat: i,
            cardSurplus: this.$u.minus(cardMoney, price),
            partner: canUseCardList.filter((j) => !i.find((k) => k.seatNo == j.seatNo) && +j.finalPrice <= this.$u.minus(cardMoney, price))
          }
        })
        console.log(finalUseCardPrice, "添加卡剩点：finalUseCardPrice")
        const filterNeedPay = finalUseCardPrice.filter((i) => i.cardSurplus >= 0 && i.partner.length === 0)
        console.log(filterNeedPay, "过滤不足抵扣+存在父集：filterNeedPay")
        const sortFilterNeedPay = filterNeedPay.sort((a, b) => {
          return this.$u.minus(a.cardSurplus, b.cardSurplus)
        })
        console.log(sortFilterNeedPay, "卡剩点排序：sortFilterNeedPay")
        const useIdx = this.isMaxCard ? sortFilterNeedPay.length - 1 : 0
        cutPrice = sortFilterNeedPay[useIdx].price
        if (this.checkParams.useVipFirstDiscount) {
          // 使用了会员折扣
          cutPrice = this.$u.minus(cutPrice, this.checkParams.vipDiscountInfo.value)
        }
      }
      this.cutPrice = cutPrice
      console.log(cutPrice, "抵扣价格：cutPrice")
    },
    doCombination(arr) {
      let count = arr.length - 1,
        val = "",
        index = 0,
        tmp = [],
        oldTmp = [],
        totalArr = []

      return doCombinationCallback(arr, 0)
      function doCombinationCallback(arr, curr_index) {
        for (val of arr[curr_index]) {
          tmp[curr_index] = val
          if (curr_index < count) {
            doCombinationCallback(arr, curr_index + 1)
          } else {
            totalArr.push(tmp)
          }

          oldTmp = tmp
          tmp = []
          for (index of oldTmp) {
            tmp.push(index)
          }
        }
        return totalArr
      }
    },
    // 获取商品订单可用卡列表
    getCardPay() {
      uni.$api.mall.getCardPay().then((res) => {
        res.list.map((item) => {
          item.money = this.$u.times(+item.point, +item.needPoint)
          // 不可用 || 不可补差且座位数被券抵扣完
          !item.usable ? this.cardUnUseList.push(item) : this.cardCanUseList.push(item)
        })
      })
    },
    handleCheck(item) {
      if (this.checkParams.filmPrice == 0 && this.couponCardMergeUse) {
        return uni.$toast("还需支付金额为零，无需补差！")
      }
      if ((!this.cardDisabled || item.isCashDiff == "1") && item.usable) {
        this.checkId = this.checkId == item.cardId ? "" : item.cardId
        this.getCutPrice()
      }
    },
    // 确认用卡
    submit() {
      const checkCard = this.getCheckCard()
      checkCard.submit = 1
      const money = this.cutPrice
      const point = this.$u.divide(this.cutPrice, checkCard.needPoint || 0)
      checkCard.money = money
      checkCard.point = point
      console.log(checkCard, "checkCard")
      store.commit("SET_CHECK_CARD", checkCard)
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped></style>
